package com.ffapp.f9164.td.fragment;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.BleLog;
import com.clj.fastble.utils.HexUtil;
import com.ffapp.f9164.td.R;
import com.ffapp.f9164.td.basis.BasisFragment;
import com.ffapp.f9164.td.basis.Constants;
import com.ffapp.f9164.td.bean.ParamListData;
import com.ffapp.f9164.td.util.CountDown;
import com.ffapp.f9164.td.util.EditTextUtil;
import com.ffapp.f9164.td.util.SoftKeyBoardListener;
import com.ffapp.f9164.td.util.SubstringUtil;
import com.ffapp.f9164.td.view.PopHandle;
import com.suke.widget.SwitchButton;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import my.BleUtils;
import my.CheckUtils;
import my.LogUtil;
import my.MySharedPreferences;
import my.TimeUtils;

public class TerminalFragment extends BasisFragment {

    static TerminalFragment fragment;

    public static TerminalFragment newInstance() {
        if (fragment == null) {
            fragment = new TerminalFragment();
        }
        return fragment;
    }


    MySharedPreferences mSp;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    MyAdapter adapter;
    ArrayList<ParamListData> terminalList;
    ArrayList<ParamListData> originalList;
    public static int SUBMIT = 75;
    private boolean isFinish = false;

    private CountDown mCountDownTimer;
    private static final long MAX_TIME = 11 * 1000;
    private StringBuffer saveResult = new StringBuffer();

    private int subPosition = 0;
    private Handler submitHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 75://75提交
                    isFinish = false;
                    if (subPosition < terminalList.size()) {
                        initSettingSaveThred(subPosition);
                        subPosition++;
                    } else {
                        BleUtils.stopNotify();
                        isFinish = true;
                        originalList.clear();
                        originalList = JSON.parseObject(JSON.toJSONString(terminalList), new TypeReference<ArrayList<ParamListData>>() {
                        }); // Json 转List
                        dismissProgress();
                        mCountDownTimer.cancel();
                        if (!TextUtils.isEmpty(saveResult.toString())) {
                            PopHandle popHandle = new PopHandle(mContext, "tips_fail", "错误信息", saveResult.toString());
                            popHandle.show();
                        } else {
                            showToast("保存成功");
                        }
                    }
                    break;
                case 76:  //检查是否传输完毕
                    try {
                        if (!isFinish && !getActivity().isFinishing()) {
                            showToast("设置失败，请重试");
                            dismissProgress();
                            BleUtils.stopNotify();
                        }
                    } catch (NullPointerException e) {
                        throw e;
                    }
                    break;
            }

        }
    };

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            LogUtil.d("终端fragment显示");
        } else {
            //相当于OnPause()
            LogUtil.d("终端fragment隐藏");
        }
    }

    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.fragment_terminal);
        mSp = new MySharedPreferences(mContext);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new MyAdapter();
        recyclerView.setAdapter(adapter);
        initCountDownTimer();
    }

    public void initCountDownTimer() {
        mCountDownTimer = new CountDown();
        mCountDownTimer.setMillisInFuture(MAX_TIME);
        mCountDownTimer.setCountdownInterval(1000);
        mCountDownTimer.setCountDownListener(new CountDown.CountDownListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onFinish() {
                submitHandler.sendEmptyMessage(Constants.CHECK_FINISH);
                //这时候可以做30秒的计时操作
//                submitHandler.sendEmptyMessageDelayed(Constants.CHECK_FINISH, 20000);
//                          submitHandler.postDelayed(Constants.SUBMIT,20000);   //20秒后执行
            }

            @Override
            public void onTick(long millisUntilFinished) {
//                mTimerTv.setText(TimeTools.getCountTimeByLong(millisUntilFinished));
            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        terminalList = new ArrayList<>();
        originalList = new ArrayList<>();
    }

    public void setList(String sMsgObjString, int type) {
        terminalList.clear();
        if (!TextUtils.isEmpty(sMsgObjString)) {

//            //设备时间
//            String excclk = SubstringUtil.subString(sMsgObjString, "+EXCCLK:");
//            terminalList.add(new ParamListData("设备时间", 4, "" + excclk, "AT+EXCCLK"));

            //软件版本号
            String deviceVersion = SubstringUtil.subString(sMsgObjString, "DeviceVersion:");
            terminalList.add(new ParamListData("软件版本号", 2, "" + deviceVersion, "", "", false));

            //设备ID
            String termAddr = SubstringUtil.subString(sMsgObjString, "Term Addr:");
            terminalList.add(new ParamListData("设备ID", 2, "" + termAddr, "", "", false));

            //设备状态
            String deviceStatus = SubstringUtil.subString(sMsgObjString, "DeviceStatus:");
            terminalList.add(new ParamListData("设备状态", 2, "" + deviceStatus, "", "", false));

            //工作模式
            String workMode = SubstringUtil.subStringDefaultZero(sMsgObjString, "Work Mode:");
            List<String> workModeList = Arrays.asList(getResources().getStringArray(R.array.workMode));
            terminalList.add(new ParamListData("工作模式", 1, "" + workModeList.get(Integer.valueOf(workMode)-1), workModeList, "AT+MOD"));

            //调试信息登记
            String debugLevel = SubstringUtil.subStringDefaultZero(sMsgObjString, "Debug Level:");
            List<String> debugLevelList = Arrays.asList(getResources().getStringArray(R.array.debugLevel));
            terminalList.add(new ParamListData("调试信息登记", 1, "" + debugLevelList.get(Integer.valueOf(debugLevel)), debugLevelList, "AT+DEBUG"));

            //中心站地址
            String centerAddr = SubstringUtil.subString(sMsgObjString, "Center Addr:");
            terminalList.add(new ParamListData("中心站地址", 2, "" + centerAddr, "AT+MADD", "", true));

            //管理员密码
            String bluetoothPwd = SubstringUtil.subString(sMsgObjString, "Manager Pwd:");
            terminalList.add(new ParamListData("管理员密码", 2, "" + bluetoothPwd, "AT+MGRPWD", "", true));

            //定时上报间隔
            String reportInt = SubstringUtil.subString(sMsgObjString, "Report Int:");
            terminalList.add(new ParamListData("定时上报时间（0~1440min）", 2, "" + reportInt, "AT+RPTINT", "", true));

            //告警上报间隔
            String alarmInt = SubstringUtil.subString(sMsgObjString, "Alarm Int:");
            terminalList.add(new ParamListData("告警上报间隔（0~1440min）", 2, "" + alarmInt, "AT+ALARMINT", "", true));

            //设备休眠间隔
            String sleepInt = SubstringUtil.subString(sMsgObjString, "Sleep Int:");
            terminalList.add(new ParamListData("设备休眠间隔（0~1440min）", 2, "" + sleepInt, "AT+SLEEPINT", "", true));

            //报文重复次数
            String repeatTimes = SubstringUtil.subString(sMsgObjString, "Repeat Times:");
            terminalList.add(new ParamListData("报文重复次数", 2, "" + repeatTimes, "AT+REPT", "", true));

            //传输协议  通信协议
            String protocol = SubstringUtil.subStringDefaultZero(sMsgObjString, "Protocol:");
            List<String> protocolList = Arrays.asList(getResources().getStringArray(R.array.protocol));
            terminalList.add(new ParamListData("传输协议", 1, "" + protocol, protocolList, "AT+PROTOCOL"));

            //调试串口配置
            terminalList.add(new ParamListData("调试串口配置", 86, "aaaa", ""));

            //设备工作波特率
            String serialBaud = SubstringUtil.subStringDefaultZero(sMsgObjString, "Serial Baud:");
            List<String> serialBaudList = Arrays.asList(getResources().getStringArray(R.array.rsBaudRate));
            terminalList.add(new ParamListData("设备工作波特率", 1, "" + serialBaud, serialBaudList, "AT+IPR"));

            //串口校验属性
            String serialCom = SubstringUtil.subStringDefaultZero(sMsgObjString, "Serial Com:");
            List<String> serialComList = Arrays.asList(getResources().getStringArray(R.array.serialCom));
            terminalList.add(new ParamListData("串口校验属性", 1, "" + serialCom, serialComList, "AT+SCOM"));


            if (type == Constants.AT_FROM_DEVICE) {
//                ArrayList<ParamListData> n = (ArrayList<ParamListData>) JSON.parseArray(a,ParamListData.class); // Json 转List
                originalList = JSON.parseObject(JSON.toJSONString(terminalList), new TypeReference<ArrayList<ParamListData>>() {
                }); // Json 转List
            }
        }

        adapter.notifyDataSetChanged();
        recyclerView.setAdapter(adapter);
    }


    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

        public MyAdapter() {

        }

        //创建新View，被LayoutManager所调用
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_terminal_item, viewGroup, false);
            return new ViewHolder(view);
        }


        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(ViewHolder viewHolder, int position) {
            viewHolder.list_item.setTag(position);
            viewHolder.bind(position);
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return terminalList == null ? 0 : terminalList.size();
        }


        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {

            @BindView(R.id.list_item)
            LinearLayout list_item;
            @BindView(R.id.tv_name)
            TextView tvName;
            @BindView(R.id.edit_text)
            EditText editText;
            @BindView(R.id.img_spanner)
            ImageView imgSpanner;
            @BindView(R.id.tv_unit)
            TextView tvUnit;
            @BindView(R.id.tv_synchro)
            TextView tvSynchro;
            @BindView(R.id.switch_btn)
            SwitchButton switchBtn;

            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
                EditTextUtil.setEditTextNoEmoji(editText);
            }

            public void bind(int position) {
                ParamListData terminalListData = terminalList.get(position);
                tvName.setText(terminalListData.getName());
                switch (terminalListData.getType()) {
                    case 1: //spinner
                        editText.setText("" + (TextUtils.isEmpty(terminalListData.getValue()) ? terminalListData.getKey() : terminalListData.getValue()));
                        editText.setHint("请选择" + terminalListData.getName());
                        imgSpanner.setVisibility(View.VISIBLE);
                        tvUnit.setVisibility(View.GONE);
                        switchBtn.setVisibility(View.GONE);
                        tvSynchro.setVisibility(View.GONE);
                        editText.setEnabled(terminalListData.isEnable());//不可编辑
                        list_item.setBackgroundResource(R.color.white);
                        break;
                    case 2:  // edit
                        editText.setText("" + terminalListData.getValue());
                        editText.setHint("请输入" + terminalListData.getName());
                        tvUnit.setVisibility(View.VISIBLE);
                        tvUnit.setText(terminalListData.getUnit());
                        imgSpanner.setVisibility(View.GONE);
                        switchBtn.setVisibility(View.GONE);
                        tvSynchro.setVisibility(View.GONE);
                        editText.setEnabled(terminalListData.isEnable());//可编辑
                        editText.setVisibility(View.VISIBLE);
                        list_item.setBackgroundResource(R.color.white);
                        break;
                    case 3:  // 开关按钮
                        switch (terminalListData.getValue()) {
                            case "0":
                                switchBtn.setChecked(false);
                                break;
                            case "1":
                                switchBtn.setChecked(true);
                                break;
                        }
                        imgSpanner.setVisibility(View.GONE);
                        tvUnit.setVisibility(View.GONE);
                        tvSynchro.setVisibility(View.GONE);
                        editText.setVisibility(View.INVISIBLE);
                        list_item.setBackgroundResource(R.color.white);
                        switchBtn.setVisibility(View.VISIBLE);
                        switchBtn.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
                            @Override
                            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                                if (isChecked == true) {
                                    editText.setText("1");
                                } else {
                                    editText.setText("0");
                                }
                            }
                        });
                        break;
                    case 4:  // 同步按钮
                        editText.setText("" + terminalListData.getValue());
                        editText.setHint("请输入" + terminalListData.getName());
                        editText.setEnabled(false);//不可编辑
                        tvSynchro.setVisibility(View.VISIBLE);
                        tvUnit.setVisibility(View.GONE);
                        imgSpanner.setVisibility(View.GONE);
                        switchBtn.setVisibility(View.GONE);
                        list_item.setBackgroundResource(R.color.white);
                        break;
                    case 86:   //分隔作用
                        imgSpanner.setVisibility(View.GONE);
                        tvUnit.setVisibility(View.GONE);
                        switchBtn.setVisibility(View.GONE);
                        editText.setVisibility(View.GONE);
                        tvSynchro.setVisibility(View.GONE);
                        list_item.setBackgroundResource(R.color.base_bg_white);
                        break;

                }
                editText.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        int curPosition = getAdapterPosition();
                        ParamListData data = terminalList.get(curPosition);
                        data.setValue(s.toString());
                    }
                });

                imgSpanner.setTag(terminalListData);
                tvSynchro.setTag(terminalListData);
            }

            @OnClick(R.id.img_spanner)
            public void showSpanner(View v) {
                SoftKeyBoardListener.hideKeyboard(getActivity());
                final ParamListData terminalListData = (ParamListData) v.getTag();
                OptionsPickerView pickerView = new OptionsPickerBuilder(mContext, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        editText.setText(terminalListData.getValues().get(options1));
                    }
                })
                        .setSubmitText("确定")//确定按钮文字
                        .setCancelText("取消")//取消按钮文字
                        .build();
                pickerView.setPicker(terminalListData.getValues());
                pickerView.show();
            }

            @OnClick(R.id.tv_synchro)
            public void synchroTime(View v) {
                String time = TimeUtils.getTimeLongToStrByFormat(System.currentTimeMillis(), "yyyy/MM/dd,HH:mm:ss") + "," + Calendar.getInstance().getTime().getDay();
                editText.setText(time);
            }
        }
    }


    @OnClick(R.id.btn_save)
    public void save() {
        final StringBuffer atShowResult = new StringBuffer();
        BleUtils.notify(new BleNotifyCallback() {
            @Override
            public void onNotifySuccess() {

            }

            @Override
            public void onNotifyFailure(BleException exception) {
                BleLog.d("下发设置打开通知操作失败");
            }

            @Override
            public void onCharacteristicChanged(byte[] data) {
                for (Byte a : data) {
                    atShowResult.append(String.format("%02X", a));
                }
                String sMes = HexUtil.hexStringToString(atShowResult.toString());
                if (sMes.contains("OK")) {
                    originalList.set(subPosition - 1, terminalList.get(subPosition - 1));
                    atShowResult.setLength(0);
                    submitHandler.sendEmptyMessage(Constants.SUBMIT);
                }else if(sMes.contains("ERROR")){
                    atShowResult.setLength(0);
                    onError();
                }
            }

            @Override
            public void onError() {
                saveResult.append(terminalList.get(subPosition - 1).getName() + "保存失败" + "\r\n");
                submitHandler.sendEmptyMessage(Constants.SUBMIT);
            }
        });

        showLoading();
        saveResult.setLength(0);
        subPosition = 0;
        submitHandler.sendEmptyMessage(Constants.SUBMIT);
    }

    public void initSettingSaveThred(final int position) {
        String url = getBlueToothUrl(terminalList.get(position));
        if (TextUtils.isEmpty(url)) {
            showToast(terminalList.get(position).getName() + "的值不能为空");
            dismissProgress();
            return;
        }
        String originalurl = getBlueToothUrl(originalList.get(position));
        if (TextUtils.isEmpty(originalurl)) {
            originalurl = "";
        }
        if (originalurl.equals(url)) {
            submitHandler.sendEmptyMessage(Constants.SUBMIT);
            return;
        }

        BleLog.d("TerminalFragment===============   " + terminalList.get(position).getName() + "通过");
        final String toSet = url;
        BleUtils.write(toSet, new BleWriteCallback() {
            @Override
            public void onWriteSuccess(final int current, final int total, final byte[] justWrite) {
                if (current == total) {
                    BleLog.d("TerminalFragment   " + terminalList.get(position).getName() + "下发设置发送成功");
                    mCountDownTimer.start();
                }
            }

            @Override
            public void onWriteFailure(final BleException exception) {
                BleLog.d("TerminalFragment   " + terminalList.get(position).getName() + "下发发送失败");
                saveResult.append(terminalList.get(position).getName() + "下发失败" + "\r\n");
                submitHandler.sendEmptyMessage(Constants.SUBMIT);
            }
        });


    }

    private String getBlueToothUrl(ParamListData data) {
        String url;
        String name = data.getName();
        String at = data.getAction();
        String value = (data.getValue() == null) ? data.getKey() : data.getValue();
        if (TextUtils.isEmpty(value) || "数据异常，请重新获取".equals(value)) {
            return null;
        }

        if ("传输协议".equals(name)) {
            switch (value) {
                case "消防协议GB26875":
                    value = "1";
                    break;
                case "电信平台私有协议":
                    value = "2";
                    break;
                case "消防协议--LoRa私有协议":
                    value = "3";
                    break;
            }
        }
        if ("工作模式".equals(name)) {
            switch (value) {
                case "兼容模式":
                    value = "1";
                    break;
                case "定时自报模式":
                    value = "2";
                    break;
            }
        }

        if ("设备工作波特率".equals(name)) {
            switch (value) {
                case "115200":
                    value = "1";
                    break;
                case "9600":
                    value = "2";
                    break;
            }
        }

        if ("调试信息登记".equals(name)) {
            switch (value) {
                case "不打印日志":
                    value = "0";
                    break;
                case "打印部分日志":
                    value = "1";
                    break;
                case "打印所有日志":
                    value = "2";
                    break;
            }
        }

//        if ("中心站地址".equals(name)) {
////            String[] splitCenterAdd = value.split(",");
//            StringBuffer sbCenterAdd = new StringBuffer();
//            if (value.length() != 8) {
//                Toast.makeText(getActivity(), "中心地址必须为4个16进制", Toast.LENGTH_LONG).show();
//                return "";
//            } else {
//                try {
//                    return HexUtil.chineseWordToGbk((at + "=" + value + "\r\n"));
//                } catch (UnsupportedEncodingException e) {
//                    e.printStackTrace();
//                }
//                value = sbCenterAdd.toString();
//            }
//        }

            if ("设备时间".equals(name)) {
                StringBuilder sb = new StringBuilder(value);//构造一个StringBuilder对象
                sb.insert(0, "\"");
                sb.insert(value.length() - 1, "\"");
                value = sb.toString();
            }


            String a = HexUtil.strToHex((at + "=" + value));
            if (CheckUtils.isContansChinese(value)) {
                try {
                    value = HexUtil.chineseWordToGbk(value);
                    a = HexUtil.strToHexNoSpace((at + "=")) + value + "0D0A";
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            return url = a;
        }


}
